package store

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"

	"torler.com/qingyue/apps/backend/internal/app/core"
	"torler.com/qingyue/common/types"
)

type Common struct {
	Container *core.Container
}

func newCommon(container *core.Container) *Common {
	return &Common{
		Container: container,
	}
}

// GetValidCode 根据难码类型和账号获取验证码
func (c *Common) GetValidCode(ctx context.Context, codeType types.ValidCodeType, target string) (string, error) {
	log := c.Container.Logger.With("codeType", codeType).With("target", target)

	r := c.Container.R
	name := fmt.Sprintf("valid_code:%s:%s", codeType.Name(), target)
	code, err := r.Get(ctx, name).Result()
	if err != nil {

		if err == redis.Nil {
			log.Error("获取验证码失败，账号不存在")
			return "", nil
		} else {
			log.Error("获取验证码失败")
			return "", err
		}

	}

	return code, nil
}

func (c *Common) SaveValidCode(ctx context.Context, codeType types.ValidCodeType, target string, code string, expire time.Duration) error {
	name := fmt.Sprintf("valid_code:%s:%s", codeType.Name(), target)
	logger := c.Container.Logger.With("codeType", codeType).With("target", target).With("name", name)

	err := c.Container.R.Set(ctx, name, code, expire).Err()
	if err != nil {
		logger.Error("保存到redis失败")
		return err
	}
	logger.Info("保存到redis成功")
	return nil
}
